package com.adgox.tiantianbiting.main;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.FileProvider;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.bean.BaseResponseBean;
import com.adgox.tiantianbiting.bean.RandomRedPacketBean;
import com.adgox.tiantianbiting.bean.SignCheckTodayBean;
import com.adgox.tiantianbiting.bean.SignWeekBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.bean.VersionBean;
import com.adgox.tiantianbiting.home.index.HomeIndexFragment;
import com.adgox.tiantianbiting.listen.index.ListenFragment;
import com.adgox.tiantianbiting.mine.index.MineFragment;
import com.adgox.tiantianbiting.mine.login.LoginActivity;
import com.adgox.tiantianbiting.net.callback.JsonCallback;
import com.adgox.tiantianbiting.redpacket.index.WelfareFragment;
import com.adgox.tiantianbiting.utils.ApiConstant;
import com.adgox.tiantianbiting.utils.DialogUtils;
import com.adgox.tiantianbiting.widget.FragmentContainer;
import com.adgox.tiantianbiting.widget.TabEntity;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.rae.swift.session.SessionManager;

import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;

public class MainActivity extends AppCompatActivity implements OnTabSelectListener, View.OnClickListener {


    @BindView(R.id.container)
    FragmentContainer mContainer;
    @BindView(R.id.tab)
    CommonTabLayout mTabLayout;
    private ArrayList<Fragment> fragments;
    private long exitTime;
    private Dialog uDialog;
    private VersionBean versionData;
    private ProgressBar progressBar;
    private String path;
    private TextView tvProgress;
    private Dialog pDialog;
    private SharedPreferences sp;
    private int userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {

        if (SessionManager.getDefault().isLogin()){
            userId = ((UserInfo) SessionManager.getDefault().getUser()).getId();
            //检测定时红包
            DialogUtils.checkRandomRed(userId,this,"首页");
        }
        //检测签到状态并弹窗
        checkSign();

        //记录登录时间
        sendLoginTime();

        //记录极光id
        sendJpushId();

        //动态申请权限
        getPermission();

        //检测版本
        checkUpdate();

        //设置tab内容
        ArrayList<CustomTabEntity> entities = new ArrayList<>();
        entities.add(new TabEntity("首页", R.drawable.icon_first_active, R.drawable.icon_first_default));
        entities.add(new TabEntity("红包", R.drawable.icon_second_default, R.drawable.icon_second_default));
        entities.add(new TabEntity("记录", R.drawable.icon_third_active, R.drawable.icon_third_default));
        entities.add(new TabEntity("我的", R.drawable.icon_forth_active, R.drawable.icon_forth_default));
        mTabLayout.setTabData(entities);

        //设置container内容
        fragments = new ArrayList<>();

        Fragment mHomeIndexFragment = HomeIndexFragment.newInstance();
        Fragment mWelfareFragment = WelfareFragment.newInstance();
        Fragment mListenFragment = ListenFragment.newInstance();
        Fragment mMineFragment = MineFragment.newInstance();

        fragments.add(mHomeIndexFragment);
        fragments.add(mWelfareFragment);
        fragments.add(mListenFragment);
        fragments.add(mMineFragment);

        mContainer.setOffscreenPageLimit(4);
        mContainer.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));

        //tab设置选择监听
        mTabLayout.setOnTabSelectListener(this);

    }

    private void checkSign() {
        if (!SessionManager.getDefault().isLogin()) {
            DialogUtils.showSignDialog(this, null);
            return;
        }
        OkGo.<BaseResponseBean<SignCheckTodayBean>>get(ApiConstant.BASE_URL + ApiConstant.CHECK_TODAY_SIGN)
                .params("userId", userId)
                .execute(new JsonCallback<BaseResponseBean<SignCheckTodayBean>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<SignCheckTodayBean>> response) {
                        if ("0".equals(response.body().getCode()) && response.body().getData() != null) {
                            SignCheckTodayBean bean = response.body().getData();
                            if (bean.getCurrentDaySignIn() == 0) {
                                getSignData();
                            }
                        }
                    }
                });
    }

    private void getSignData() {
        OkGo.<BaseResponseBean<List<SignWeekBean>>>get(ApiConstant.BASE_URL + ApiConstant.GET_SIGN_LIST)
                .params("userId", userId)
                .params("flg", 1)
                .execute(new JsonCallback<BaseResponseBean<List<SignWeekBean>>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<List<SignWeekBean>>> response) {
                        if ("0".equals(response.body().getCode()) && response.body().getData() != null) {
                            SignWeekBean signWeekBean = response.body().getData().get(0);
                            DialogUtils.showSignDialog(MainActivity.this, signWeekBean);
                        }
                    }
                });
    }

    private void sendJpushId() {
        JPushInterface.init(this);
        String registrationID = JPushInterface.getRegistrationID(this);
        SharedPreferences sp = getSharedPreferences("jpush", MODE_PRIVATE);
        //保存在本地的，对应当前设备极光id的用户id
        int userId = sp.getInt("userId", -1);

        //如果没登录，且本地没有保存记录，就直接传单独的极光id过去
        if (!SessionManager.getDefault().isLogin()) {
            if (userId == -1) {
                postJpush(registrationID, 0);
            }
            //如果本地有保存记录，则不做处理
            return;
        }

        //当前用户id
        int id = ((UserInfo) SessionManager.getDefault().getUser()).getId();

        //如果本地没有保存记录，或者本地保存id和当前id不一致，传
        if (userId == -1 || userId != id) {
            postJpush(registrationID, id);
        }

        //将传过去的userid保存到本地
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("userId", id);
        editor.commit();
    }

    private void postJpush(String jId, int userId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("jpushId", jId);
        if (userId > 0) map.put("userId", userId);
        Gson gson = new Gson();
        String s = gson.toJson(map);

        OkGo.<String>post(ApiConstant.BASE_URL + ApiConstant.POST_JPUSH_ID)
                .upJson(s)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //不管成功失败，都不处理了
                    }
                });
    }

    private void sendLoginTime() {
        //只有是登录状态才记录
        if (SessionManager.getDefault().isLogin()) {
            OkGo.<String>get(ApiConstant.BASE_URL + ApiConstant.LOGIN_RECORD)
                    .params("operationTypeId", 1)
                    .params("userId", ((UserInfo) SessionManager.getDefault().getUser()).getId())
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                        }
                    });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //收集imei
        sendImei();

    }

    private void getPermission() {
        String[] permissions = new String[]{
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission_group.STORAGE,
        };
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, permissions, 777);
        }
    }

    private void sendImei() {
        if (!SessionManager.getDefault().isLogin()) return;

        sp = getSharedPreferences("imei", MODE_PRIVATE);
        String imei = sp.getString("imei", null);
        final String newImei = getimei();
        if (newImei != null && !newImei.equals(imei)) {
            OkGo.<BaseResponseBean<String>>get(ApiConstant.BASE_URL + ApiConstant.SEND_IMEI)
                    .params("platType", "android")
                    .params("deviceNumber", newImei)
                    .params("userId", ((UserInfo) SessionManager.getDefault().getUser()).getId())
                    .execute(new JsonCallback<BaseResponseBean<String>>() {
                        @Override
                        public void onSuccess(Response<BaseResponseBean<String>> response) {
                            if ("0".equals(response.body().getCode())) {
                                SharedPreferences.Editor editor = sp.edit();
                                editor.putString("imei", newImei);
                                editor.commit();
                            }
                        }
                    });
        }
    }

    private String getimei() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
            String imei = telephonyManager.getDeviceId();
            return imei;
        } else {
            return null;
        }
    }

    private void checkUpdate() {
        OkGo.<BaseResponseBean<VersionBean>>get(ApiConstant.BASE_URL + ApiConstant.CHECK_UPDATE + "android")
                .execute(new JsonCallback<BaseResponseBean<VersionBean>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<VersionBean>> response) {
                        versionData = response.body().getData();
                        if (!"0".equals(response.body().getCode()) || versionData == null) {
                            Toast.makeText(MainActivity.this, "检测版本失败", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        int currentVersionCode = getCurrentVersionCode();
                        if (currentVersionCode < versionData.getVersionCode()) {
                            popUpdateDialog(versionData);
                        }
                    }
                });
    }

    //检测当前版本号
    private String getCurrentVersion() {
        try {
            return this.getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "1.0.0";
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if ("listen".equals(intent.getStringExtra("flg"))){
            //跳转收藏页
            mTabLayout.setCurrentTab(2);
            mContainer.setCurrentItem(2);
        } else if ("home".equals(intent.getStringExtra("flg"))){
            //跳转首页
            mTabLayout.setCurrentTab(0);
            mContainer.setCurrentItem(0);
        }
    }

    //检测当前版本名
    private int getCurrentVersionCode() {
        try {
            return this.getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    //弹出更新框
    private void popUpdateDialog(VersionBean data) {
        uDialog = new Dialog(this);
        Window window = uDialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        uDialog.setContentView(R.layout.dialog_update);
        TextView newVer = uDialog.findViewById(R.id.tv_newVer);
        TextView cuVer = uDialog.findViewById(R.id.tv_cuVer);
        TextView tvConfirm = uDialog.findViewById(R.id.tv_confirm);
        TextView tvCancel = uDialog.findViewById(R.id.tv_cancel);

        newVer.setText("最新版本:" + data.getVersion());
        cuVer.setText("当前版本:" + getCurrentVersion());

        tvConfirm.setOnClickListener(this);
        tvCancel.setOnClickListener(this);

        uDialog.setCanceledOnTouchOutside(false);

        uDialog.show();
    }

    @Override
    public void onTabSelect(int position) {
        if (position == 2) {
            if (!SessionManager.getDefault().isLogin()) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        }
        mContainer.setCurrentItem(position, false);
    }

    @Override
    public void onTabReselect(int position) {
        //不作处理
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_confirm:
                uDialog.dismiss();
                toUpdate();
                break;
            case R.id.tv_cancel:
                uDialog.dismiss();
        }
    }

    //下载更新资源
    private void toUpdate() {
        if (versionData == null || versionData.getDownloadUrl() == null) return;

        //弹出下载进度条
        popDownloadDialog();

        //文件保存路径
        path = this.getExternalFilesDir("update").getAbsolutePath();

        //开始下载
        OkGo.<File>get(versionData.getDownloadUrl())
                .execute(new FileCallback(path, "tiantianbiting.apk") {
                    @Override
                    public void onSuccess(Response<File> response) {
                        pDialog.dismiss();
                        installApk();
                    }

                    @Override
                    public void downloadProgress(Progress progress) {
                        super.downloadProgress(progress);
                        if (progressBar != null && tvProgress != null) {
                            progressBar.setMax((int) progress.totalSize);
                            progressBar.setProgress((int) progress.currentSize);

                            NumberFormat numberFormat = NumberFormat.getInstance();
                            numberFormat.setMaximumFractionDigits(2);
                            String format = numberFormat.format((float) progress.currentSize / (float) progress.totalSize * 100);
                            tvProgress.setText("下载中" + format + "%");
                        }
                    }
                });
    }

    //下载完毕自动安装
    private void installApk() {
        File apkFile = new File(path, "tiantianbiting.apk");
        if (!apkFile.exists()) {
            return;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            Uri uri = FileProvider.getUriForFile(this, "com.adgox.tiantianbiting.installapk", apkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            Uri uri = Uri.parse("file://" + apkFile.toString());
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }


        startActivity(intent);
    }

    private void popDownloadDialog() {
        pDialog = new Dialog(this);
        Window window = pDialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        pDialog.setContentView(R.layout.dialog_progress);
        progressBar = pDialog.findViewById(R.id.id_progress);
        tvProgress = pDialog.findViewById(R.id.tv_progress);
        pDialog.setCanceledOnTouchOutside(false);
        pDialog.show();
    }

    //FragmentContainer的适配器
    private class ViewPagerAdapter extends FragmentStatePagerAdapter {
        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

    }

    //点击返回键处理，按两次返回键退出

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
//            System.exit(0);
            moveTaskToBack(true);
        }
    }
}
